<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import api from '@/api/chat'

export default {
  name: 'App',
  data() {
    return {
      timer: null,
      ws: null,
      ready_data: {
        socketUrl: '',
        maxReconnectTimes: 3
      }
    }
  },
  mounted() {
    if (getToken()) {
      api.ready({
        bsff: 'admin_notify'
      }).then(res => {
        if (res.code === 0) {
          this.ready_data = res.data
          this.initWebSocket()
        }
      })
    }

  },
  beforeDestroy() {
    this.leave = true
    this.closeWebSocket()
  },
  destroyed() {
    this.leave = true
    this.closeWebSocket()
  },
  methods: {
    closeWebSocket() {
      if (this.ws) {
        this.ws.close()
        this.ws = null
      }
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval)
        this.heartbeatInterval = null
      }
    },
    initWebSocket() {
      const that = this
      const wsUrl = this.ready_data.socketUrl
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket 连接已建立')
        //发送登录信息
        const token = getToken()
        this.ws.send(JSON.stringify({
          type: 'listen-msg',
          token: token
        }))

        // 设置心跳检测定时器
        this.heartbeatInterval = setInterval(() => {
          console.log('发送心跳检测')
          that.ws.send(JSON.stringify({ type: 'ping' }))
        }, 30000)
      }

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        console.log(message)
        if (message.type === 'notify') {
          this.$notify({
            title: message.title,
            message: message.content,
            duration: message.duration || 1000,
            type: message.notify_type || 'info',
            onClick: () => {
              if (message.link) {
                this.$router.push(message.link)
              }
              console.log('WebSocket 消息点击', message)
            }
          })
        }

      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭')
        // 可以在这里尝试重新连接
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
      }
    }
  }

}
</script>
 <style>
 .el-row.row-action-btns{
    display: flex;
    align-items: center;
    justify-content: space-evenly;
 }
</style>
